package com.hashbee.bbs.service.impl;


import com.alibaba.fastjson.JSON;
import com.hashbee.bbs.bo.*;
import com.hashbee.bbs.bo.para.PageQueryPara;
import com.hashbee.bbs.bo.para.PostPara;
import com.hashbee.bbs.dao.*;
import com.hashbee.bbs.domain.*;
import com.hashbee.bbs.service.PostService;
import com.hashbee.bo.ReturnData;
import com.hashbee.user.model.UserVo;
import com.hashbee.util.Common;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("postService")
public class PostServiceImpl implements PostService {

    @Autowired
    private PostsMapper postsMapper;

    @Autowired
    private TagsMapper tagsMapper;

    @Autowired
    private ForumMapper forumMapper;

    @Autowired
    private PostTagMapper postTagMapper;

    @Autowired
    private NotificationMapper notificationMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private PostLikeMapper postLikeMapper;

    /**
     * 创建/回复帖子
     * @param postPara 帖子参数
     * @return
     */
    @Override
    @Transactional(transactionManager = "hashbeeTxMgr")
    public ReturnData<String> create(PostPara postPara) {

        ReturnData<String> returnData = new ReturnData<>();
        UserVo user;
        try {
            user = (UserVo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            returnData.setStatus(1007);
            returnData.setMessage("未登录");
            return returnData;
        }

        // 标题转义
        postPara.setSubject(StringEscapeUtils.unescapeHtml4(postPara.getSubject()));

        postPara.setUserId(user.getId().toString());
        String postId = UUID.randomUUID().toString().replace("-", "");
        String parentId = postPara.getParentId();
        postPara.setPostId(postId);
        if (parentId != null) {
            // 是回帖，需要获取目录帖子信息
            Posts targetPost = this.queryDetail(parentId);
            postPara.setParentId(parentId);
            Notification notification = new Notification();
            notification.setTitle("您的问题有新的回复");
            notification.setContent("您的问题: "+ targetPost.getSubject() +"，有新的回复");
            notification.setTargetId(postPara.getUserId());
            notification.setTargetType("user");
            notificationMapper.insert(notification);
        } else {
            // 新帖
            postPara.setParentId(postId);
        }

        // 创建帖子数据
        postsMapper.insert(postPara);
        // 更新forum帖子数量
        forumMapper.increasePostCount(postPara.getForumId());
        // 如果是回帖，更新目标帖的回复数
        if (parentId != null) {
            postsMapper.increaseReplyCount(parentId);
        }

        // 处理标签
        String tagString = postPara.getTags();
        if (!"".equals(tagString)) {
            List<Tags> tagsList = new ArrayList<>();
            List<PostTag> postTagList = new ArrayList<>();
            String[] tagArray = tagString.split(",");
            for (String tagName : tagArray) {
                Tags tags = new Tags();
                tags.setName(tagName);
                tagsList.add(tags);

                PostTag postTag = new PostTag();
                postTag.setPostId(postId);
                postTag.setName(tagName);
                postTagList.add(postTag);
            }
            // 创建或更新标签
            tagsMapper.insertDuplicateIncreaseUseCount(tagsList);
            // 建立或更新post与tag的关系
            Map<String, List<PostTag>> postTagListMap = new HashMap<>();
            postTagListMap.put("postTagList", postTagList);
            postTagMapper.insertDuplicate(postTagListMap);
        }

        // 如果有categoryId，增加对应category的post_count
        if (postPara.getCategoryId() > 0) {
            categoryMapper.increasePostCount(postPara.getCategoryId());
        }

        returnData.setData(postId);

        return returnData;
    }

    /**
     * 分页获取主题列表
     * @param pageQueryPara 参数对象
     * @return
     */
    @Override
    public PageData<Posts> queryTopic(PageQueryPara pageQueryPara) {

        //PagePosts pagePosts = new PagePosts();
        PageData<Posts> postsPageData = new PageData<>();

        ArrayList<Posts> postsList = postsMapper.selectTopic(pageQueryPara);
        Common common = new Common();
        ArrayList<String> postIdList = new ArrayList<>();
        for (Posts posts : postsList) {
            if (posts.getCover() != null) {
                try {
                    Avatar cover = JSON.parseObject(posts.getCover(), Avatar.class);
                    posts.setCover(common.getAvatarUrl(cover));
                } catch (Exception e){
                    posts.setCover("");
                }
            }

            if (posts.getAvatarUrl() != null) {
                try {
                    Avatar avatar = JSON.parseObject(posts.getAvatarUrl(), Avatar.class);
                    posts.setAvatarUrl(common.getAvatarUrl(avatar));
                } catch (Exception e) {
                    //posts.setAvatar("");
                }
            }

            postIdList.add(posts.getPostId());
        }

        // 获取标签
        Map<String, List<PostTag>> postTagMap = null;
        List<PostTag> postTagList = postTagMapper.selectByPostId(postIdList);
        if (postTagList != null) {
            postTagMap = new HashMap<>();
            for (PostTag postTag : postTagList) {
                List<PostTag> postTagListItem;
                if (!postTagMap.containsKey(postTag.getPostId())) {
                    postTagListItem = new ArrayList<>();
                    postTagListItem.add(postTag);
                } else {
                    postTagListItem = postTagMap.get(postTag.getPostId());
                    postTagListItem.add(postTag);
                }
                postTagMap.put(postTag.getPostId(), postTagListItem);
            }


        }

        // 获取访问用户对帖子的喜欢数据
        UserVo user = null;
        try {
            user = (UserVo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
        }
        Map<String, UserIsLike> userIsLikeMap = null;
        if (user != null) {
            userIsLikeMap = new HashMap<>();
            Map<String, Object> userLikeMap = new HashMap<>();
            userLikeMap.put("userId", user.getId().toString());
            userLikeMap.put("postIdList", postIdList);
            List<PostLike> postLikeList = postLikeMapper.selectByUserIdAndInPostId(userLikeMap);
            if (postLikeList != null) {
                for (PostLike postLike : postLikeList) {
                    UserIsLike userIsLike = new UserIsLike();
                    switch (postLike.getIsLike()) {
                        case 1:
                            userIsLike.setIsLike(1);
                            break;
                        case -1:
                            userIsLike.setIsHate(1);
                    }
                    userIsLikeMap.put(postLike.getPostId(), userIsLike);
                }
            }
        }

        if (postTagMap != null || userIsLikeMap != null) {
            // 遍历帖子列表，将对应的标签赋给它
            for (Posts posts : postsList) {
                if (postTagMap != null) {
                    if (postTagMap.containsKey(posts.getPostId())) {
                        posts.setPostTagList(postTagMap.get(posts.getPostId()));
                    }
                }

                if (userIsLikeMap != null) {
                    if (userIsLikeMap.containsKey(posts.getPostId())) {
                        UserIsLike userIsLike = userIsLikeMap.get(posts.getPostId());
                        if (userIsLike.getIsLike() == 1) {
                            posts.setIsLike(1);
                        }

                        if (userIsLike.getIsHate() == 1) {
                            posts.setIsHate(1);
                        }
                    }
                }
            }
        }

        postsPageData.setList(postsList);
        //pagePosts.setList(postsList);

        Integer count = postsMapper.selectTopicCount(pageQueryPara);
        //pagePosts.setCount(count);
        postsPageData.setCount(count);

        return postsPageData;
    }

    /**
     * 帖子详情
     * @param postId 帖子ID
     * @return
     */
    @Override
    public Posts queryDetail(String postId) {

        Posts posts = postsMapper.selectByPrimaryKey(postId);
        if (posts != null) {
            Common common = new Common();
            if (posts.getCover() != null) {
                try {
                    Avatar cover = JSON.parseObject(posts.getCover(), Avatar.class);
                    posts.setCover(common.getAvatarUrl(cover));
                } catch (Exception e){
                    posts.setCover("");
                }
            }

            if (posts.getAvatarUrl() != null) {
                try {
                    Avatar avatar = JSON.parseObject(posts.getAvatarUrl(), Avatar.class);
                    posts.setAvatarUrl(common.getAvatarUrl(avatar));
                } catch (Exception e) {
                    //posts.setAvatar("");
                }
            }

            // 获取标签
            List<String> postIdList = new ArrayList<>();
            postIdList.add(postId);
            List<PostTag> postTagList = postTagMapper.selectByPostId(postIdList);
            posts.setPostTagList(postTagList);

            // 更新阅读数
            postsMapper.increaseViewCount(postId);
            posts.setViewCount(posts.getViewCount() + 1);
        }
        return posts;
    }

    @Override
    public PagePosts queryReply(PageQueryPara pageQueryPara) {

        PagePosts pagePosts = new PagePosts();
        ArrayList<Posts> postsList = postsMapper.selectReply(pageQueryPara);
        Common common = new Common();
        ArrayList<String> postIdList = new ArrayList<>();
        for (Posts posts : postsList) {
            if (posts.getCover() != null) {
                try {
                    Avatar cover = JSON.parseObject(posts.getCover(), Avatar.class);
                    posts.setCover(common.getAvatarUrl(cover));
                } catch (Exception e){
                    posts.setCover("");
                }
            }

            if (posts.getAvatarUrl() != null) {
                try {
                    Avatar avatar = JSON.parseObject(posts.getAvatarUrl(), Avatar.class);
                    posts.setAvatarUrl(common.getAvatarUrl(avatar));
                } catch (Exception e) {
                    //posts.setAvatar("");
                }
            }

            postIdList.add(posts.getPostId());
        }

        // 获取访问用户对帖子的喜欢数据
        UserVo user = null;
        try {
            user = (UserVo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
        }
        Map<String, UserIsLike> userIsLikeMap = null;
        if (user != null) {
            userIsLikeMap = new HashMap<>();
            Map<String, Object> userLikeMap = new HashMap<>();
            userLikeMap.put("userId", user.getId().toString());
            userLikeMap.put("postIdList", postIdList);
            List<PostLike> postLikeList = postLikeMapper.selectByUserIdAndInPostId(userLikeMap);
            if (postLikeList != null) {
                for (PostLike postLike : postLikeList) {
                    UserIsLike userIsLike = new UserIsLike();
                    switch (postLike.getIsLike()) {
                        case 1:
                            userIsLike.setIsLike(1);
                            break;
                        case -1:
                            userIsLike.setIsHate(1);
                    }
                    userIsLikeMap.put(postLike.getPostId(), userIsLike);
                }
            }
        }

        if (userIsLikeMap != null) {
            // 遍历帖子列表，将对应的标签赋给它
            for (Posts posts : postsList) {
                if (userIsLikeMap.containsKey(posts.getPostId())) {
                    UserIsLike userIsLike = userIsLikeMap.get(posts.getPostId());
                    if (userIsLike.getIsLike() == 1) {
                        posts.setIsLike(1);
                    }

                    if (userIsLike.getIsHate() == 1) {
                        posts.setIsHate(1);
                    }
                }
            }
        }

        pagePosts.setList(postsList);

        Integer count = postsMapper.selectCount(pageQueryPara);
        pagePosts.setCount(count);

        return pagePosts;
    }

    @Override
    @Transactional(transactionManager = "hashbeeTxMgr")
    public ReturnData<Integer> like(IsLike isLike) {
        ReturnData<Integer> returnData = new ReturnData<>();
        UserVo user;
        try {
            user = (UserVo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            returnData.setStatus(1007);
            returnData.setMessage("未登录");
            return returnData;
        }

        isLike.setUserId(user.getId().toString());

        PostLike postLike = postLikeMapper.selectByUserIdAndPostId(isLike);
        if (postLike == null) {
            // 没有记录，根据传入值创建/修改数据
            if (isLike.getIsLike() == 1 || isLike.getIsLike() == 0) {
                isLike.setLiked(1);
                isLike.setIsLike(1);
            } else if(isLike.getIsLike() == -1) {
                isLike.setHated(1);
            }
        } else {
            // 已有记录，判断各种情况
            if (postLike.getIsLike() == 1) {
                if (isLike.getIsLike() == -1) {
                    isLike.setHated(1);
                } else {
                    isLike.setIsLike(0);
                }
                isLike.setLiked(-1);
            } else if (postLike.getIsLike() == -1) {
                if (isLike.getIsLike() == 1) {
                    isLike.setLiked(1);
                } else {
                    isLike.setIsLike(0);
                }
                isLike.setHated(-1);
            } else {
                if (isLike.getIsLike() == 1 || isLike.getIsLike() == 0) {
                    isLike.setLiked(1);
                    isLike.setIsLike(1);
                } else if (isLike.getIsLike() == -1) {
                    isLike.setHated(1);
                }
            }
        }

        // 创建like表数据
        postLikeMapper.insert(isLike);
        // 更新post表数据
        postsMapper.updateLikeOrHate(isLike);

        return returnData;
    }
}
